package com.algorithm.cn.one;

import java.util.Arrays;

/**
 * 
 * @author wangzonghui
 * @date 2020年5月26日 下午5:02:57 
 * @Description:二分查找
 */
public class BinarySearch {
	
	public static void main(String[] args) {
		int[] whitelist = {12,87,97,32,998,3332};
		Arrays.sort(whitelist);
		int key=87;
		System.out.println(rank(key,whitelist));
		
	}
	
	/**
	 * 二分查找
	 * @param key 要查找对象
	 * @param a 待查找数组
	 * @return
	 */
	public static int rank(int key,int[] a) {
		int lo=0;
		int hi=a.length-1;
		while( lo <= hi) {
			int mid = lo+(hi - lo) / 2;
			if (key < a[mid]) 
			hi=mid-1;
			else if(key > a[mid])
			lo = mid +1;
			else return mid;
		}
		return -1;
	}

}
